/**
 * 
 */
package util;

import java.io.File;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;

import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;

import sun.misc.BASE64Decoder;

/**
 * @author luohc
 * <p>
 * 上传下载工具类，使用单例实现
 * </p>
 * <p>
 * 1.解析上传配置文件
 * </p>
 */
public class PlUploadUtil {

    // upload.xml相对于web根目录的路径
    private final static String UPLOAD_FILE_PATH = "upload.xml";
    private static PlUploadUtil util;
    private Map<String, String> uploadParam;
    private String              rootPath;

    private PlUploadUtil(String rootPath) throws Exception {
        this.rootPath = rootPath;
        uploadParam = getUploadParams();
    }

    /**
     * @return 键值对形式储存的配置文件参数 解析upload.xml配置文件为键值对形式
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public Map<String, String> getUploadParams() throws Exception {
        Map<String, String> uploadParams = new HashMap<String, String>();
        try {
            SAXReader reader = new SAXReader();
            Document document = reader.read(new File(rootPath + "/" + UPLOAD_FILE_PATH));
            Element root = document.getRootElement();

            for (Iterator<Element> rt = root.elementIterator(); rt.hasNext();) {
                Element r_pe = (Element) rt.next();
                uploadParams.put(r_pe.getName(), r_pe.getText());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new Exception("读取upload.xml 文件异常");
        }
        return uploadParams;
    }

    public Map<String, String> getUploadParam() {
        return uploadParam;
    }

    /**
     * @param rootPath 项目绝对路径
     * @return 工具类实例 单例实现
     * @throws Exception
     */
    public synchronized static PlUploadUtil getInstance(String rootPath) throws Exception {
        if (util == null) {
            util = new PlUploadUtil(rootPath);
        }
        return util;
    }

    // 将 s 进行 BASE64 编码
    public static String getBASE64(String s) {
        if (s == null) return null;
        return (new sun.misc.BASE64Encoder()).encode(s.getBytes());
    }

    // 将 BASE64 编码的字符串 s 进行解码
    public static String getFromBASE64(String s) {
        if (s == null) return null;
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            byte[] b = decoder.decodeBuffer(s);
            return new String(b);
        } catch (Exception e) {
            return null;
        }
    }

}
